import {
	defineStore,
	storeToRefs
} from "pinia";
import api from "@/api";
import {
	useUserStoreToRefs
} from "@/store/useUserStore";
import BigNumber from "bignumber.js"; // 浮点数运算插件
import {
	reactive
} from "vue";

export const useCartStore = defineStore("cart", {
	state: () => ({
		brandSaleList: [], //即将开售商品
		brandInvalidList: [], //失效列表
		brandCartList: [], //商品列表
		brandOrderList: [], //下单列表
		brandsRefereeList: [],
		carLen: 0, //购物车商品数量
	}),
	actions: {
		//加入购物车
		async addCart(msg) {
			const {
				userInfo
			} = useUserStoreToRefs();
			// const msg = {
			// 	addType:4, 购物车操作类型 1:商品列表处添加,2:购物车列表处添加,3提交订单后需要删除的,4:删除购物车某个商品,5,用户未登录之前添加的购物车, 6-购物车更换规格
			// 	arr:this.brandCartList, 操作的数据
			// 	arrType:2,数据是否嵌套
			// 	ifRadio:true,是否需要判断勾选
			//  isSelect:true,根据购物车显示选中与否，false表示加入及选中
			// };
			console.log(msg)
			let params = {
				storeId: msg.storeId,
				goodsType: msg.goodsType,
				addType: msg.addType,
				shoppingCarList: [],
			};

			switch (msg.arrType) {
				case 1: //单成数据
					msg.arr.forEach((item) => {
						params.shoppingCarList.push({
							id: item.id,
							amount: item.amount,
							isLettering: item.isLettering,
							letteringMsg: item.letteringMsg,
							skuCode: item.skuCode,
							removeSkuCode: item.removeSkuCode,
							isSelect: msg.isSelect ? (item.radio ? 1 : 0) : 1,
							refereeId: msg.addType == 1 ? userInfo.value.id : "",
						});
					});
					break;
				case 2: //确认订单多嵌套数据
					msg.arr.forEach((item) => {
						if (!item.shoppingCarVOlist) {
							item.shoppingCarVOlist = item.shopData;
						}

						item.shoppingCarVOlist.forEach((itemChild) => {
							params.shoppingCarList.push({
								id: itemChild.id,
								amount: itemChild.amount,
								isLettering: itemChild.isLettering,
								letteringMsg: itemChild.letteringMsg,
								skuCode: itemChild.skuCode,
								removeSkuCode: item.removeSkuCode,
								isSelect: msg.isSelect ? (itemChild.radio ? 1 : 0) :
									1,
								refereeId: msg.addType == 1 ? userInfo.id : "",
							});
						});
					});
					break;
			}
			const res = await api({
				method: "POST",
				url: `/mall/shopping/goods/car`,
				data: params,
			});
			if (msg.addType == 1) {
				this.carLen = this.carLen + params.shoppingCarList[0].amount;
			} else {
				this.getLength(this.brandCartList);
			}

			return res;
		},
		// 进来时获取购物车数量
		async getGartList(msg) {
			const {
				userInfo
			} = useUserStoreToRefs();
			return new Promise(async (resolve, rej) => {
				if (userInfo.value.id) {
					//登录时获取购物车列表
					let res;
					const params = {
						brandId: "",
					};
					res = await api({
						method: "get",
						url: `/mall/shopping/goods/v2/car`,
					});
					res = res.data;
					if (res.length <= 0) {
						this.clearCartData()
						uni.hideLoading();
						resolve([]);
						return null;
					}
					let resData = res;

					let data = {
						data: resData,
						userInfo: userInfo,
					};
					var res2 = await this.getNewProductMsg(data);
					let arr = []; //失效商品
					let arr2 = []; //预售商品
					let arr3 = []; //有效商品
					// //筛选失效商品 已下架 限购人群 数量超出 售罄 商品被删除 规格不存在
					res2.forEach((item, i) => {
						item.shoppingCarVOlist.forEach((itemChild, j) => {
							if (
								itemChild.status == 2 ||
								itemChild.isError1 ||
								itemChild.isError2 ||
								(itemChild.stocks == 0 && itemChild
									.prepareStocks == 0) ||
								itemChild.delFlag == 1 ||
								itemChild.skuStatus == 0 ||
								itemChild.skuDelFlag == 1 || 
								itemChild.purchaseUserLimit==1&&itemChild.purchaseUserLevels.indexOf(userInfo.value.identity)==-1
							) {
								arr.push(itemChild);
							} else if (itemChild.status == 0) {
								//单独列出的预售
								arr2.push(itemChild);
							} else {
								arr3.push(itemChild);
							}
						});
					});
					//排列有效商品
					let arr3List = [];
					arr3.forEach((item, i) => {
						if (arr3List.length <= 0) {
							let obj = {
								brandsName: item.brandsName,
								brandsLogo: item.brandsLogo,
								haveCoupon: item.haveCoupon,
								maxDiscountCoupon: item.maxDiscountCoupon,
								shoppingCarVOlist: [item],
							};
							arr3List.push(obj);
						} else {
							let obj = {
								brandsName: item.brandsName,
								haveCoupon: item.haveCoupon,
								brandsLogo: item.brandsLogo,
								maxDiscountCoupon: item.maxDiscountCoupon,
								shoppingCarVOlist: [item],
							};
							arr3List.push(obj);
						}
					});
					arr3List.forEach((item) => {
						item.radio = true;
						item.shoppingCarVOlist.forEach((citem) => {
							citem.radio = citem.isSelect ? true : false;
							item.brandsId = citem.brandsId;
							citem.discountPrice = "0.00";
							if (!citem.radio) {
								item.radio = false;
							}
							const count = new BigNumber(citem.price)
								.times(citem.amount)
								.toNumber(); // 计算总价
							if (citem.radio && citem.discountMoney != count) {
								citem.discountPrice = new BigNumber(citem.price)
									.minus(citem.discountMoney || 0)
									.div(citem.amount)
									.toFixed(2);
							}
						});
					});
					this.brandSaleList = arr2;
					this.brandInvalidList = arr;
					this.brandCartList = arr3List;
					this.getLength(arr3List);
					resolve(arr3List);
				} else {
					this.clearCartData()
					resolve([]);
				}
				uni.hideLoading();
			});
		},
		//更新商品
		//isSelect 在确认订单时传 1,表示默认为勾选状态
		//comboRefereeId 分享商品的推荐人ID
		async getNewProductMsg(msgInfo) {
			let {
				data,
				userInfo,
				isSelect,
				comboRefereeId
			} = msgInfo;
			const params = common.handleShoppingCartParams(
				data,
				userInfo,
				isSelect,
				comboRefereeId
			);
			//处理从购物车列表获取的数据
			var res2 = await api({
				method: "PUT",
				url: `/mall/shopping/goods/V2021/v3/shopping-car`,
				data: JSON.stringify(params),
			});
			res2 = res2.data;
			//整理商品类型
			if (res2.length > 0) {
				this.brandsRefereeList = res2[0].brandsRefereeList;
				res2.forEach((item) => {
					item.shoppingCarVOlist.forEach((itemChild) => {
						itemChild.haveCoupon = item.haveCoupon;
						itemChild.maxDiscountCoupon = item.maxDiscountCoupon;
						itemChild = common.productStatus(itemChild);
					});
				});
			}
			return res2;
		},
		//获取购物车数量
		getLength(value) {
			let arr = value.reduce((pre, cur) => {
				return pre.concat(cur.shoppingCarVOlist);
			}, []);
			const length = arr.reduce((pre, cur) => {
				return pre + Number(cur.amount);
			}, 0);
			this.carLen = length;
		},
		// 清除购物车数据
		clearCartData() {
			this.brandSaleList = []
			this.brandInvalidList = []
			this.brandCartList = []
			this.brandOrderList = []
			this.carLen = 0
		},
		//删除数据
		delectPro(){
			const data = {
				addType: 4,
				arr: this.brandOrderList,
				arrType: 1,
				ifRadio: false,
				isRequest: true,
				isSelect:true
			};
			this.addCart(data);
		},
		getPresalesDelivery(goodInfo){
			common.getPresalesDelivery(goodInfo)
		},
		limitAmount: (item, value) => {
			let inputvalue = value;
			var num =
				item.purchaseLimitType == 1 ?
				Number(item.purchaseLimitRules.split(",")[1]) :
				Number(item.purchaseLimitRules);
			var numberBig = num - Number(item.alreadyBuyNum ? item.alreadyBuyNum : 0);
			if (Number(item.purchaseLimitType) >= 1 && value > numberBig) {
				inputvalue = numberBig;
			}
			if (item.stocks + item.prepareStocks <= inputvalue) {
				inputvalue = item.stocks + item.prepareStocks;
			}
			if (inputvalue <= 1) {
				inputvalue = 1;
			}
			return inputvalue;
		},
	},
	persist: {
		storage: {
			getItem: (key) => uni.getStorageSync(key),
			setItem: (key, value) => uni.setStorageSync(key, value),
		},
	},
});

const common = reactive({
	timer:null,
	handleShoppingCartParams: (data, userInfo, isSelect) => {
		const params = data.map(item => {
			// 时间处理
			let dateParams;
			if (item.addTime) {
				item.addTime = item.addTime.replace(/\-/g, '/')
				dateParams = new Date(item.addTime);

			} else {
				dateParams = new Date();
			}
			let dateTime = dateParams.setHours(dateParams.getHours() + 8);
			let dataTimeIos = new Date(dateTime).toISOString();
			dataTimeIos = dataTimeIos.substr(0, dataTimeIos.length - 1);
			let refereeId = ''
			let obj = {
				type: userInfo.userType,
				userId: userInfo.id,
				id: item.id,
				amount: item.amount,
				addTime: dataTimeIos,
				isLettering: item.isLettering,
				letteringMsg: item.letteringMsg,
				skuCode: item.skuCode,
				isSelect: isSelect || item.isSelect,
				refereeId,
				storeId: item.storeId
			}
			if (item.upgradeConfigId) {
				obj.upgradeConfigId = item.upgradeConfigId
			}
			return obj
		})

		return params
	},
	productStatus: (itemChild) => {
		const {userInfo} = useUserStoreToRefs();
		//判断预售时间是否到期
		if (itemChild.status == 0 && itemChild.saleTime) {
			let curTime = new Date().getTime();
			itemChild.saleTime = itemChild.saleTime.replace(/\-/g, "/");
			let endTime = new Date(itemChild.saleTime).getTime();
			if (endTime <= curTime) {
				itemChild.status = null;
			}
		}
		if (itemChild.status == 0) {
			itemChild.openStatus2 = "即将开售";
			itemChild.openColor2 = "#FF4C4E";
			// itemChild.isPredict = true; //外部处理倒计时
			itemChild.disabled = true;
			const presalesDelivery = common.getPresalesDelivery(itemChild);
			itemChild.isPredict = itemChild.deliveryTimeType == 0 ?presalesDelivery :`${itemChild.deliveryMsg}`;
		}
		if (
			itemChild.saleType == 3 ||
			(itemChild.stocks == 0 && itemChild.saleType == 2) ||
			(itemChild.stocks == 0 && itemChild.prepareStocks > 0) ||
			itemChild.presellOn == 1
		) {
			itemChild.openStatus3 = "预售";
			itemChild.openColor3 = "#FF4C4E";
			const presalesDelivery = common.getPresalesDelivery(itemChild);
			itemChild.isPredict =
				itemChild.deliveryTimeType == 0 ?
				presalesDelivery :
				`${itemChild.deliveryMsg}`;
		}
		//运营在后台删除了商品
		if (itemChild.delFlag == 1) {
			itemChild.invalidIntro = "商品不存在";
			return itemChild;
		}
		//商品下架
		if (itemChild.status == 2) {
			itemChild.invalidIntro = "商品已下架";
			return itemChild;
		}
		// 售卖完毕
		if (itemChild.stocks == 0 && itemChild.prepareStocks == 0) {
			itemChild.invalidStatus = false;
			itemChild.sellOut = true;
			itemChild.disabled = true;
			itemChild.invalidIntro = "商品已抢光";
			return itemChild;
		}
		//规格禁用
		if (itemChild.skuStatus == 0 || itemChild.skuDelFlag == 1) {
			itemChild.invalidIntro = "规格不存在";
			return itemChild;
		}
		if (itemChild.oneBuyPromotionVO) {
			itemChild.invalidIntro = "价格已失效";
			return itemChild;
		}
		if(itemChild.purchaseUserLevels&&itemChild.purchaseUserLevels.indexOf(userInfo.value.identity)==-1){
			itemChild.invalidIntro = `暂不支持${userInfo.value.identity==0?'陪宠师':userInfo.value.identity==1?'店长':'普通用户'}购买`;
			return itemChild;
		}
		//是否已达购买数量
		if (common.getLimitStatus(itemChild)) {
			itemChild.isError2 = true;
			itemChild.errorMessag =
				common.getLimitTime(
					itemChild.purchaseLimitType,
					itemChild.purchaseLimitRules,
					1
				) +
				(itemChild.alreadyBuyNum ?
					`(已购${itemChild.alreadyBuyNum ? itemChild.alreadyBuyNum : "0"}件)` :
					"");

			itemChild.invalidIntro = "已购数量已达限购上限";
			return itemChild;
		}

		return itemChild;
	},
	
	// 预售商品发货方式
	getPresalesDelivery: (goodInfo = {}) => {
		// 判断是否为预售
		const isPresell = goodInfo.saleType == 3 || (goodInfo.stocks == 0 && goodInfo.saleType == 2) || (
			goodInfo.stocks ==
			0 &&
			goodInfo.prepareStocks > 0) || goodInfo.presellOn == 1
		if (goodInfo && (isPresell || goodInfo.openStatus3) && goodInfo.prepareDeliveryTime) {
			let monthPart
			const prepareDeliveryTimeComponent = goodInfo.prepareDeliveryTime.split(',')
			const month = prepareDeliveryTimeComponent[0].split('-')[1]
			switch (Number(prepareDeliveryTimeComponent[2])) {
				case 1:
					monthPart = "上旬"
					break;
				case 2:
					monthPart = "中旬"
					break;
				case 3:
					monthPart = "下旬"
					break;
			}
			return `预售，${Number(month)}月${monthPart}发货`
		} else if (goodInfo && (isPresell || goodInfo.openStatus3) && goodInfo.deliveryMsg) {
			if (goodInfo.deliveryTimeType == 0) {
				let time = goodInfo.deliveryMsg.split('-')[0] + '年' + goodInfo.deliveryMsg.split('-')[1] +
					'月' + goodInfo
					.deliveryMsg.split('-')[2] + '日后开始发货'
				return time
			} else {
				return goodInfo.deliveryMsg
			}
		}
		return false
	},
	getLimitStatus: (product) => {
		//限购数量是否超标
		if (product.purchaseLimitType == 0 || product.isLimit == 1) {
			return false;
		}

		if (product.purchaseLimitType) {
			var num =
				product.purchaseLimitType == 1 ?
				Number(product.purchaseLimitRules.split(",")[1]) :
				Number(product.purchaseLimitRules);
			var syNum =
				product.purchaseLimitType >= 1 ?
				num -
				Number(product.alreadyBuyNum == null ? 0 : product.alreadyBuyNum) :
				"";
			return product.purchaseLimitType != 0 && syNum <= 0;
		}
	},

	//purchaseLimitType 0不限购 1按时间限购 2永久限购
	getLimitTime: (purchaseLimitType, purchaseLimitRules, type) => {
		if (purchaseLimitType != 0) {
			if (purchaseLimitType == 1) {
				var arr = purchaseLimitRules.split(",");
			}
			var num = purchaseLimitType == "1" ? arr[1] : purchaseLimitRules;
			if (purchaseLimitType == 1) {
				if (arr[0] == 7) {
					var day = "每周";
				} else if (arr[0] == 1) {
					var day = "每天";
				} else {
					var day = "每月";
				}
			} else {
				var day = ""; //永久
			}
			if (type == 1) {
				return day + "限购" + num + "件";
			}
		}
	}
})


export const useCartStoreToRefs = () => {
	return storeToRefs(useCartStore());
};


export const resetUseCartStore = () => {
	useCartStore().$reset();
};